package com.mgq.netty.c6;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Scanner;

@Slf4j
public class NettyClientCloseFuture {
    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup group = new NioEventLoopGroup();
        //1.启动类
        ChannelFuture channelFuture = new Bootstrap()
                //2.添加EventLoop
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                    }
                })
                .connect(new InetSocketAddress("localhost", 8080));
        //方式二:交给其他线程处理
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            //操作完成时调用
            public void operationComplete(ChannelFuture future) throws Exception {
                Channel channel = future.channel();
                log.debug("channel:{}",channel);
            }
        });
        Channel channel = channelFuture.channel();
        new Thread(() -> {
            Scanner scanner = new Scanner(System.in);
            while (true) {
                String s = scanner.nextLine();
                //关闭channel
                if ("q".equals(s)) {
                    channel.close();
                    break;
                }
                channel.writeAndFlush(s);
            }
        }, "input").start();

        //channel关闭后,还需要进行一些其他操作,我们可以调用channel.closeFuture();
        //然后添加addListener
        ChannelFuture future = channel.closeFuture();
        //获取CloseFuture对象.关闭有2种方式,同步关闭,异步关闭
        future.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                log.debug("channel已关闭,后续操作........");
                //优雅关闭
                group.shutdownGracefully();
            }
        });
    }
}
